
import os
import zipfile
from pathlib import Path

def convert_size(size_bytes):
    """将字节数转换为可读格式"""
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size_bytes < 1024.0:
            return f"{size_bytes:.1f}{unit}"
        size_bytes /= 1024.0
    return f"{size_bytes:.1f}TB"

def recursive_unzip(zip_path, extract_to):
    """迭代解压ZIP文件"""
    stack = [(zip_path, extract_to)]
    
    while stack:
        current_zip, current_dir = stack.pop()
        with zipfile.ZipFile(current_zip, 'r', metadata_encoding='gbk') as zip_ref:
            zip_ref.extractall(current_dir)
            # os.remove(current_zip)
        
        # 检查解压后的文件中是否还有ZIP文件
        for root, _, files in os.walk(current_dir):
            for file in files:
                if file.endswith('.zip'):
                    nested_zip = os.path.join(root, file)
                    stack.append((nested_zip, root+"/"+file.split(".")[0]))

def get_file_tree(directory):
    """获取解压后的文件树结构"""
    file_list = []
    print_dir = os.path.dirname(directory)
    for root, _, files in os.walk(directory):
        for file in files:
            if file.endswith('.zip'):
                continue
            file_path = os.path.join(root, file)
            size = os.path.getsize(file_path)
            file_list.append({
                'name': os.path.relpath(file_path, print_dir),
                'size': convert_size(size)
            })
    return file_list

def main(zip_file_path, output_dir=None):
    """主函数"""
    if output_dir is None:
        output_dir = os.path.splitext(zip_file_path)[0]
    
    Path(output_dir).mkdir(parents=True, exist_ok=True)
    recursive_unzip(zip_file_path, output_dir)
    return get_file_tree(output_dir)

if __name__ == '__main__':
    # 示例用法
    zip_path = 'D:/KC-软件工程/20250919ZY/backend/uploads/zip/1760019719.zip'  # 替换为你的ZIP文件路径
    result = main(zip_path)
    print(result)
